package com.tomcov.client.activities;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.widget.WidgetComponent;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.cell.client.ActionCell;
import com.google.gwt.cell.client.ActionCell.Delegate;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.maps.client.base.ElementProvider;
import com.google.gwt.maps.client.base.HasElementProvider;
import com.google.gwt.maps.client.base.HasLatLng;
import com.google.gwt.maps.client.directions.DirectionsCallback;
import com.google.gwt.maps.client.directions.DirectionsRenderer;
import com.google.gwt.maps.client.directions.DirectionsRequest;
import com.google.gwt.maps.client.directions.DirectionsService;
import com.google.gwt.maps.client.directions.DirectionsTravelMode;
import com.google.gwt.maps.client.directions.HasDirectionsLeg;
import com.google.gwt.maps.client.directions.HasDirectionsRequest;
import com.google.gwt.maps.client.directions.HasDirectionsResult;
import com.google.gwt.maps.client.directions.HasDirectionsService;
import com.google.gwt.maps.client.directions.HasDirectionsStep;
import com.google.gwt.maps.client.directions.HasDirectionsTravelMode;
import com.google.gwt.maps.client.directions.impl.DirectionsRendererImpl;
import com.google.gwt.maps.client.event.Event;
import com.google.gwt.maps.client.event.HasMouseEvent;
import com.google.gwt.maps.client.event.MouseEventCallback;
import com.google.gwt.maps.client.geocoder.Geocoder;
import com.google.gwt.maps.client.geocoder.GeocoderCallback;
import com.google.gwt.maps.client.geocoder.GeocoderRequest;
import com.google.gwt.maps.client.geocoder.HasGeocoder;
import com.google.gwt.maps.client.geocoder.HasGeocoderRequest;
import com.google.gwt.maps.client.geocoder.HasGeocoderResult;
import com.google.gwt.maps.client.overlay.HasMarker;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.maps.client.overlay.impl.MarkerImpl;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.tomcov.client.ClientFactory;
import com.tomcov.client.Ressource.TomCovRes;
import com.tomcov.client.i18n.MapViewConstants;
import com.tomcov.client.i18n.MessageViewConstants;
import com.tomcov.client.place.WelcomPlace;
import com.tomcov.client.service.JourneyServiceAsync;
import com.tomcov.client.view.MapView;
import com.tomcov.shared.Journey;
import com.tomcov.shared.JourneyPassenger;
import com.tomcov.shared.Message;
import com.tomcov.shared.UserInfo;

public class MapActivity extends AbstractActivity implements MapView.Presenter{

	private ClientFactory clientFactory;
	private HasGeocoder Mygeocoder;
	//private HasDirectionsResult directionsDriver = new DirectionsResult(null);
	private final DirectionsRenderer directionsRenderer = new DirectionsRenderer();
	private List<String> steps;
	private List<String> listAddress = null;
	private final List<HasMarker> overlays = new ArrayList<HasMarker>();
	private List<String> waypointsCoords;
	private List<String> passengersTravels = new ArrayList<String>();
	private float detour;
	private String idnumber;
	private int counter=0;
	private Date arrival;
	private Date deptime2;
	private Date deptime1;
	private Date date;
	private String fromAddress;
	private String toAddress;
	private String mapUrl;
	private double distance;
	private double duration;
	private Element imEO = null;
	private Element imED = null;
	private final MapViewConstants mapviewconstants = GWT.create(MapViewConstants.class);
	private final TomCovRes TomCovRes = GWT.create(TomCovRes.class);

	/**
	 * Instantiates a new map activity.
	 *
	 * @param clientFactory the client factory
	 */
	public MapActivity(ClientFactory clientFactory){
		this.clientFactory = clientFactory;	
	}


	public void affichenodriver(){
		MapView mapView = clientFactory.getMapView();
		VerticalPanel Cellcontainer=mapView.getPossibleUserPanel();
		Cellcontainer.clear();
		TomCovRes tomtom = GWT.create(TomCovRes.class);
		HorizontalPanel pnl = new HorizontalPanel();
		Image warning = new Image(tomtom.NotOk());
		Label lb = new Label(mapviewconstants.noDriverfound());
		lb.addStyleName("label");
		pnl.add(warning);
		pnl.add(lb);
		pnl.addStyleName("warningpanel");
		Cellcontainer.add(pnl);
	}

	public void affichenopassenger(){
		MapView mapView = clientFactory.getMapView();
		VerticalPanel Cellcontainer=mapView.getPossibleUserPanel();
		Cellcontainer.clear();
		TomCovRes tomtom = GWT.create(TomCovRes.class);
		HorizontalPanel pnl = new HorizontalPanel();
		Image warning = new Image(tomtom.NotOk());
		Label lb = new Label(mapviewconstants.nopassengerfound());
		lb.addStyleName("label");
		pnl.add(warning);
		pnl.add(lb);
		pnl.addStyleName("warningpanel");
		Cellcontainer.add(pnl);

	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		MapView mapView = clientFactory.getMapView();
		bindRadiobutton();
		suggestboxdemerde();
		mapView.getRoadButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				MapView mapView = clientFactory.getMapView();
				mapView.getRoadButton().setVisible(false);
				mapView.getDirectionsPanel().clear();
				getRoad();
				mapView.getRoadButton().setVisible(true);
			}
		});
		mapView.getAddJourneyButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				MapView mapView = clientFactory.getMapView();
				mapView.getAddJourneyButton().setEnabled(false);
				mapView.getPossibleUserPanel().clear();
				try{
					if(isNotOk() ==false){
						getinsession();
					}
				}
				catch(NumberFormatException e){Window.alert("fill all the field");}
				mapView.getAddJourneyButton().setEnabled(true);
			}
		});

		mapView.setPresenter(this);
		panel.setWidget(mapView.asWidget());
	}

	private boolean isNotOk() {
		MapView mapView = clientFactory.getMapView();
		boolean a = ( mapView.getArrivalTime().getValue()== null || mapView.getDeptime1().getValue()==null
				|| mapView.getDeptime2().getValue()==null || mapView.getDate().getValue()==null
				|| mapView.getDetour()<=0);
		return a;
	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);		
	}

	private void suggestboxdemerde(){
		final MapView mapview=clientFactory.getMapView();

		((SuggestBox) (mapview.getOriginField().getWidget())).getTextBox().addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent event) {

				WidgetComponent imageOk = new WidgetComponent(new Image(TomCovRes.Ok()));
				WidgetComponent imageNotOK = new WidgetComponent(new Image(TomCovRes.NotOk()));
				if (mapview.getOriginField().getValue() != null) {
					if (imEO != null)
						mapview.getOriginField().el().getParent().dom.removeChild(imEO);
					imageOk.render(mapview.getOriginField().el().getParent().dom);
					imEO = mapview.getOriginField().el().getParent().dom.appendChild(imageOk.getElement());
					imageOk.el().alignTo(mapview.getOriginField().getElement(),"tl-tr", new int[] { 2, 3 });
				} else {
					if (imEO != null)
						mapview.getOriginField().el().getParent().dom.removeChild(imEO);
					imageNotOK.render(mapview.getOriginField().el().getParent().dom);
					imEO = mapview.getOriginField().el().getParent().dom.appendChild(imageNotOK.getElement());

					imageNotOK.el().alignTo(mapview.getOriginField().getElement(),"tl-tr", new int[] { 2, 3 });

				}
			}
		});
		((SuggestBox) (mapview.getDestinationField().getWidget())).getTextBox()
		.addBlurHandler(new BlurHandler() {

			@Override
			public void onBlur(BlurEvent event) {

				WidgetComponent imageValid = new WidgetComponent(new Image(TomCovRes.Ok()));
				WidgetComponent imageInvalid = new WidgetComponent(new Image(TomCovRes.NotOk()));
				if (mapview.getDestinationField().getValue() != null) {
					if (imED != null)
						mapview.getDestinationField().el().getParent().dom.removeChild(imED);
					imageValid.render(mapview.getDestinationField().el().getParent().dom);
					imED = mapview.getDestinationField().el().getParent().dom.appendChild(imageValid.getElement());
					imageValid.el().alignTo(mapview.getDestinationField().getElement(),"tl-tr", new int[] { 2, 3 });

				} else {
					if (imED != null)
						mapview.getDestinationField().el().getParent().dom.removeChild(imED);
					imageInvalid.render(mapview.getDestinationField().el().getParent().dom);
					imED = mapview.getDestinationField().el().getParent().dom.appendChild(imageInvalid.getElement());
					imageInvalid.el().alignTo(mapview.getDestinationField().getElement(),"tl-tr", new int[] { 2, 3 });
				}
			}
		});
		//add click listener to the map
		MouseEventCallback mapClickCallback = new MouseEventCallback() {
			@Override
			public void callback(HasMouseEvent event) {
				HasLatLng point = event.getLatLng();
				HasMarker marker;
				if(counter==0){
					marker = new Marker();
					marker.setPosition(point);
					marker.setMap(mapview.getMap().getMap());
					whereAmI(point);
					overlays.add(marker);
					counter++;

				}else if(counter==1){
					marker = new Marker();
					marker.setPosition(point);
					marker.setMap(mapview.getMap().getMap());
					whereAmI(point);
					overlays.add(marker);
					counter++;
				}
				else if(counter==2){
					cleanMeUp();
					counter = 0;
				}

			}
		};
		Event.addListener(mapview.getMap().getMap(), "click", mapClickCallback);

		//Add suggest box to the destination fields
		mapview.getFromAddress().addKeyUpHandler(new KeyUpHandler(){

			@Override
			public void onKeyUp(KeyUpEvent event) {
				Mygeocoder = new Geocoder();
				HasGeocoderRequest MyRequest = new GeocoderRequest();
				MyRequest.setRegion("be");
				MyRequest.setLanguage("fr");
				MyRequest.setAddress(mapview.getFromAddress().getText());

				Mygeocoder.geocode(MyRequest, new GeocoderCallback(){
					@SuppressWarnings("deprecation")
					@Override
					public void callback(List<HasGeocoderResult> responses,String status) {
						MultiWordSuggestOracle suggestbox = (MultiWordSuggestOracle) mapview.getFromAddress().getSuggestOracle();
						for (HasGeocoderResult param: responses){
							suggestbox.add(param.getFormattedAddress());
						}
						mapview.getFromAddress().showSuggestionList();

					}
				});
			}
		});

		mapview.getToAddress().addKeyUpHandler(new KeyUpHandler(){

			@Override
			public void onKeyUp(KeyUpEvent event) {
				Mygeocoder = new Geocoder();
				HasGeocoderRequest MyRequest = new GeocoderRequest();
				MyRequest.setRegion("be");
				MyRequest.setLanguage("fr");
				MyRequest.setAddress(mapview.getToAddress().getText());

				Mygeocoder.geocode(MyRequest, new GeocoderCallback(){
					@SuppressWarnings("deprecation")
					@Override
					public void callback(List<HasGeocoderResult> responses,String status) {
						MultiWordSuggestOracle suggestbox = (MultiWordSuggestOracle) mapview.getToAddress().getSuggestOracle();
						for (HasGeocoderResult param: responses){
							suggestbox.add(param.getFormattedAddress());
						}
						mapview.getToAddress().showSuggestionList();

					}
				});
			}
		});


	}

	private void bindRadiobutton(){
		MapView mapview=clientFactory.getMapView();
		mapview.getDriverRadioButton().addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				MapView mapview=clientFactory.getMapView();
				mapview.getPassengerRadioButton().setValue(false);

			}
		});
		mapview.getPassengerRadioButton().addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				MapView mapview=clientFactory.getMapView();
				mapview.getDriverRadioButton().setValue(false);
			}
		});

	}

	@SuppressWarnings("deprecation")
	private void whereAmI(HasLatLng point) {
		final MapView mapview=clientFactory.getMapView();
		Mygeocoder = new Geocoder();
		HasGeocoderRequest request = new GeocoderRequest();
		request.setLatLng(point);
		Mygeocoder.geocode(request, new GeocoderCallback() {

			@Override
			public void callback(List<HasGeocoderResult> responses,String status) {
				if (counter == 1) {
					mapview.getFromAddress().setText(responses.get(0).getFormattedAddress());
				} else if (counter == 2) {
					mapview.setToAddress(responses.get(0).getFormattedAddress());
				}

			}

		});
	}

	private void cleanMeUp(){
		for (int i = 0; i < overlays.size(); i++) {
			if (overlays.get(i).getClass() == Marker.class)
				MarkerImpl.impl.setMap(overlays.get(i).getJso(), null);
		}
	}

	private int getRoad() {
		final MapView mapview = clientFactory.getMapView();
		HasDirectionsService directionsService = new DirectionsService();
		DirectionsRendererImpl.impl.setMap(directionsRenderer.getJso(),null);
		directionsRenderer.setMap(mapview.getMap().getMap());
		HasElementProvider element = new ElementProvider(mapview.getDirectionsPanel().getElement());
		directionsRenderer.setPanel(element);
		HasDirectionsRequest directionsRequest = new DirectionsRequest();
		HasDirectionsTravelMode travelMode = new DirectionsTravelMode();
		directionsRequest.setTravelMode(travelMode.Driving());
		directionsRequest.setOriginString(mapview.getFromAddress().getText());
		directionsRequest.setDestinationString(mapview.getToAddress().getText());

		directionsService.route(directionsRequest, new DirectionsCallback() {
			@Override
			public void callback(HasDirectionsResult response, String status) {
				directionsRenderer.setDirections(response);
				//directionsDriver = response;
				steps = new ArrayList<String>();
				duration=0;
				distance=0;
				for (HasDirectionsLeg leg : response.getRoutes().get(0).getLegs()) {
					duration =duration+ leg.getDuration().getValue();
					distance =distance+ leg.getDistance().getValue();
					for (HasDirectionsStep step : leg.getSteps()) {
						for (int j = 0; j < step.getPath().size(); j = j + 4) {
							steps.add(step.getPath().get(j).toUrlValue());
						}
					}
				}
				mapview.getDistance().setText(mapviewconstants.distance() + ": "+ distance + " m. ");
				mapview.getDuration().setText(mapviewconstants.duration()+ ": "+ DateTimeFormat.
						getFormat("HH:mm:ss").format(new Date((long) duration * 1000),TimeZone.createTimeZone(0)));
				mapUrl = "http://maps.google.com/maps/api/staticmap?size=300x300&path=color:0x0000ff";
				for (String step : steps) {
					mapUrl = mapUrl+ "%7C" + step;
				}
				mapUrl = mapUrl+ "&sensor=false";
			}
		});
		return 1;
	}

	@SuppressWarnings("deprecation")
	private void initialiseCst(UserInfo user){
		fromAddress= clientFactory.getMapView().getFromAddress().getText();
		toAddress=clientFactory.getMapView().getToAddress().getValue();
		MapView mapview=clientFactory.getMapView();
		detour = (float) mapview.getDetour();

		arrival=new Date();
		arrival=mapview.getDate().getValue();
		arrival.setHours(Integer.valueOf(mapview.getArrivalTime().getValue().substring(0,2)));
		arrival.setMinutes(Integer.valueOf(mapview.getArrivalTime().getValue().substring(3,5)));
		deptime2=new Date();
		deptime2=mapview.getDate().getValue();
		deptime2.setHours(Integer.valueOf(mapview.getDeptime2().getValue().substring(0,2)));
		deptime2.setMinutes(Integer.valueOf(mapview.getDeptime2().getValue().substring(3,5)));
		deptime1=new Date();
		deptime1=mapview.getDate().getValue();
		deptime1.setHours(Integer.valueOf(mapview.getDeptime1().getValue().substring(0,2)));
		deptime1.setMinutes(Integer.valueOf(mapview.getDeptime1().getValue().substring(3,5)));
		date =new Date();
		date = mapview.getDate().getValue();
		//date.setHours(Integer.valueOf(mapview.getDeptime1().getValue().substring(0,2)));
		//	date.setMinutes(Integer.valueOf(mapview.getDeptime1().getValue().substring(3,5)));

		if(clientFactory.getMapView().getDriverRadioButton().getValue()==true){
			JourneyMaker2(user);
		}
		else{
			JourneyPassengerMaker(user);
		}
	}

	private void JourneyMaker2(final UserInfo user){
		final Journey j= new Journey(fromAddress,toAddress,user.getUserName(),date);
		j.setDistance(distance);
		j.setDuration(duration);
		j.setHeureArr(arrival);
		j.setHeuredep(deptime1);
		j.setHeurede2(deptime2);
		j.setSteps(listAddress);
		j.setStepsDetails(steps);
		j.setPlace(user.getPlace());
		j.setWaypoints(waypointsCoords);
		j.setPassengerList(passengersTravels);
		j.setDetour(detour);
		addJourneyAsDriver(user,j);

	}

	private void addJourneyAsDriver(final UserInfo uder,Journey journey) {

		JourneyServiceAsync JSA =clientFactory.getJSA();

		JSA.AddJourney(journey,new AsyncCallback<Journey>(){
			@Override
			public void onFailure(Throwable caught) {
				try{
					throw caught;
				}
				catch(NullPointerException e){
					Window.alert("fail to add journey");	
				}
				catch (Throwable e) {
					Window.alert("fail to add journey");	
					e.printStackTrace();
				}	
			}
			@Override
			public void onSuccess(Journey result) {
				if(result==null){
					Window.alert("non added. maybe your already doing something at this date");
				}
				else{
					Window.alert("journey add");
					idnumber=result.getId();
					getPossiblePassenger(result);
				}
			}
		});		
	}

	private void JourneyPassengerMaker(UserInfo user){
		JourneyPassenger j= new JourneyPassenger();
		j.setPassenger(user.getUserName());
		j.setDistance(distance);
		j.setDuration(duration);
		j.setDate(date);
		j.setHeureArr(arrival);
		j.setHeuredep(deptime1);
		j.setHeurede2(deptime2);
		j.setFrom(fromAddress);
		j.setTo(toAddress);
		j.setSteps(listAddress);
		j.setStepsDetails(steps);
		j.setWaypoints(waypointsCoords);
		addJourneyAsPassenger(user,j);

	}

	private void addJourneyAsPassenger(UserInfo user,JourneyPassenger j){
		clientFactory.getJPSA().addJourney(j, new AsyncCallback<JourneyPassenger>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("server fail to addjourneypass");
			}
			@Override
			public void onSuccess(JourneyPassenger result) {
				if(result==null){
					Window.alert("you're already doing something at this time");
				}
				else{
					idnumber=result.getId();
					Window.alert("journeypass add");
					getPossibleDriver(result);
				}
			}
		});
	}

	private void getinsession(){
		final MapView mapview = clientFactory.getMapView();
		HasDirectionsService directionsService = new DirectionsService();
		DirectionsRendererImpl.impl.setMap(directionsRenderer.getJso(),null);
		directionsRenderer.setMap(mapview.getMap().getMap());
		HasElementProvider element = new ElementProvider(mapview.getDirectionsPanel().getElement());
		directionsRenderer.setPanel(element);
		HasDirectionsRequest directionsRequest = new DirectionsRequest();
		HasDirectionsTravelMode travelMode = new DirectionsTravelMode();
		directionsRequest.setTravelMode(travelMode.Driving());
		directionsRequest.setOriginString(mapview.getFromAddress().getText());
		directionsRequest.setDestinationString(mapview.getToAddress().getText());

		directionsService.route(directionsRequest, new DirectionsCallback() {
			@Override
			public void callback(HasDirectionsResult response, String status) {
				directionsRenderer.setDirections(response);
				steps = new ArrayList<String>();
				duration=0;
				distance=0;
				for (HasDirectionsLeg leg : response.getRoutes().get(0).getLegs()) {
					duration =duration+ leg.getDuration().getValue();
					distance =distance+ leg.getDistance().getValue();
					for (HasDirectionsStep step : leg.getSteps()) {
						for (int j = 0; j < step.getPath().size(); j = j + 4) {
							steps.add(step.getPath().get(j).toUrlValue());
						}
					}
				}
				mapview.getDistance().setText(mapviewconstants.distance() + ": "+ distance + " m. ");
				mapview.getDuration().setText(mapviewconstants.duration()+ ": "+ DateTimeFormat.
						getFormat("HH:mm:ss").format(new Date((long) duration * 1000),TimeZone.createTimeZone(0)));
				mapUrl = "http://maps.google.com/maps/api/staticmap?size=300x300&path=color:0x0000ff";
				for (String step : steps) {
					mapUrl = mapUrl+ "%7C" + step;
				}
				mapUrl = mapUrl+ "&sensor=false";
				System.out.println(mapUrl);
				
				clientFactory.getUSA().getUserInSession(new AsyncCallback<UserInfo>(){
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("fail to get in session");
						goTo(new WelcomPlace(null));
					}
					@Override
					public void onSuccess(UserInfo result) {
						if (result==null){goTo(new WelcomPlace(null));}
						else{
							initialiseCst(result);

						}
					}			
				});
			}
		});
	}

	private void getPossibleDriver(final JourneyPassenger jp){
		clientFactory.getJSA().getJourneyAtTheDameDate(jp, new AsyncCallback<List<Journey>>(){

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("fail to get at the samme time");
				affichenodriver();
			}

			@Override
			public void onSuccess(List<Journey> result) {
				if(result==null){Window.alert("null at the samme time");
				affichenodriver();
				}
				else{
					ArrayList<Journey> add = new ArrayList<Journey>();
					clientFactory.getMapSA().chercheurDriver(add,jp, result, new AsyncCallback<List<Journey>>(){

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("fail to  chercheurdriver");
						}

						@Override
						public void onSuccess(List<Journey> result) {
							if(result==null){
								Window.alert("null at the chercheurdriver");
								affichenodriver();
							}
							else if(result.size()==0){
								Window.alert("null at the chercheurdriver");
								affichenodriver();
							}
							else{
								System.out.println(result.get(0).getDriver());
								displaycelltablepassenger(result);

							}

						}

					});
				}
			}
		});
	}

	private void getPossiblePassenger(final Journey j){

		clientFactory.getJPSA().getJourneyAtSameDate(j, new AsyncCallback<List<JourneyPassenger>>(){

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("fail to get at the samme time");
				affichenopassenger();
			}

			@Override
			public void onSuccess(List<JourneyPassenger> result) {
				if(result==null){
					affichenopassenger();
				}
				else{
					ArrayList<Journey> add = new ArrayList<Journey>();
					clientFactory.getMapSA().chercheurPassager(add,j, result, new AsyncCallback<List<JourneyPassenger>>(){

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("fail to  chercheurpass");

						}

						@Override
						public void onSuccess(List<JourneyPassenger> result) {
							if(result==null || result.size()==0){
								Window.alert("null at the chercheurpass");
								affichenopassenger();
							}
							else{
								System.out.println(result.get(0).getPassenger());
								displaycelltabledriver(result);
							}

						}

					});

				}
			}

		});
	}

	private void displaycelltablepassenger(List<Journey> result){

		MapView mapView = clientFactory.getMapView();
		VerticalPanel Cellcontainer=mapView.getPossibleUserPanel();
		Cellcontainer.clear();
		if( result==null){
			affichenodriver();
		}
		else{
			CellTable<Journey> celltable = new CellTable<Journey>();
			celltable.setPageSize(5);

			TextColumn<Journey> DriverColumn = new TextColumn<Journey>() {
				@Override
				public String getValue(Journey object) {
					return object.Driver;
				}
			};
			celltable.addColumn(DriverColumn, "Driver");
			DriverColumn.setSortable(true);

			TextColumn<Journey> FromColumn = new TextColumn<Journey>() {
				@Override
				public String getValue(Journey object) {
					return object.From;
				}
			};
			celltable.addColumn(FromColumn, "From");
			FromColumn.setSortable(true);

			TextColumn<Journey> ToColumn = new TextColumn<Journey>() {
				@Override
				public String getValue(Journey object) {
					return object.To;
				}
			};
			celltable.addColumn(ToColumn, "To");
			ToColumn.setSortable(true);

			DateCell dateCell = new DateCell();
			Column<Journey,Date> DateColumn = new Column<Journey,Date>(dateCell) {
				@Override
				public Date getValue(Journey object) {
					return object.date;
				}
			};
			celltable.addColumn(DateColumn, "Date");
			DateColumn.setSortable(true);


			SimplePager pager = new SimplePager();
			pager.setDisplay(celltable);
			Cellcontainer.add(pager);
			Cellcontainer.add(celltable);

			ListDataProvider<Journey> dataProvider = new ListDataProvider<Journey>();
			// Connect the table to the data provider.
			dataProvider.addDataDisplay(celltable);
			List<Journey> list = dataProvider.getList();
			for (Journey contact :  result) {
				list.add(contact);
			}

			ListHandler<Journey> FromcolumnSortHandler = new ListHandler<Journey>(list);
			FromcolumnSortHandler.setComparator(FromColumn,
					new Comparator<Journey>() {
				public int compare(Journey o1, Journey o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.From.compareTo(o2.From) : 1;}
					return -1;
				}
			});

			ListHandler<Journey> TocolumnSortHandler = new ListHandler<Journey>(list);
			TocolumnSortHandler.setComparator(ToColumn,
					new Comparator<Journey>() {
				public int compare(Journey o1, Journey o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.To.compareTo(o2.To) : 1;}
					return -1;
				}
			});

			ListHandler<Journey> DatecolumnSortHandler = new ListHandler<Journey>(list);
			DatecolumnSortHandler.setComparator(DateColumn,
					new Comparator<Journey>() {
				public int compare(Journey o1, Journey o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.date.compareTo(o2.date) : 1;}
					return -1;
				}
			});

			ListHandler<Journey> DrivercolumnSortHandler = new ListHandler<Journey>(list);
			DatecolumnSortHandler.setComparator(DriverColumn,
					new Comparator<Journey>() {
				public int compare(Journey o1, Journey o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.Driver.compareTo(o2.Driver) : 1;}
					return -1;
				}
			});


			celltable.addColumnSortHandler(FromcolumnSortHandler);
			celltable.addColumnSortHandler(TocolumnSortHandler);
			celltable.addColumnSortHandler(DatecolumnSortHandler);
			celltable.addColumnSortHandler(DrivercolumnSortHandler);


			if(clientFactory.getMapView().getPassengerRadioButton().getValue()==true){
				celltable.addColumn( new Column<Journey, Journey>(new ActionCell<Journey>( "add yourself as passenger", 
						new Delegate<Journey>( ){
					@Override
					public void execute(Journey object) {
						adddrivertojourney(object,idnumber);
					}
				}))
				{@Override
					public Journey getValue(Journey object) {
					return object;
				}
				} );
			}
		}
	}

	private void displaycelltabledriver(List<JourneyPassenger> result){

		MapView mapView = clientFactory.getMapView();
		VerticalPanel Cellcontainer=mapView.getPossibleUserPanel();
		Cellcontainer.clear();
		if(result==null){
			affichenopassenger();
		}
		else{
			CellTable<JourneyPassenger> celltable = new CellTable<JourneyPassenger>();
			celltable.setPageSize(5);

			TextColumn<JourneyPassenger> DriverColumn = new TextColumn<JourneyPassenger>() {
				@Override
				public String getValue(JourneyPassenger object) {
					return object.Passenger;
				}
			};
			celltable.addColumn(DriverColumn, "Passenger");
			DriverColumn.setSortable(true);

			TextColumn<JourneyPassenger> FromColumn = new TextColumn<JourneyPassenger>() {
				@Override
				public String getValue(JourneyPassenger object) {
					return object.From;
				}
			};
			celltable.addColumn(FromColumn, "From");
			FromColumn.setSortable(true);

			TextColumn<JourneyPassenger> ToColumn = new TextColumn<JourneyPassenger>() {
				@Override
				public String getValue(JourneyPassenger object) {
					return object.To;
				}
			};
			celltable.addColumn(ToColumn, "To");
			ToColumn.setSortable(true);

			DateCell dateCell = new DateCell();
			Column<JourneyPassenger,Date> DateColumn = new Column<JourneyPassenger,Date>(dateCell) {
				@Override
				public Date getValue(JourneyPassenger object) {
					return object.date;
				}
			};
			celltable.addColumn(DateColumn, "Date");
			DateColumn.setSortable(true);


			SimplePager pager = new SimplePager();
			pager.setDisplay(celltable);
			Cellcontainer.add(pager);
			Cellcontainer.add(celltable);

			ListDataProvider<JourneyPassenger> dataProvider = new ListDataProvider<JourneyPassenger>();
			// Connect the table to the data provider.
			dataProvider.addDataDisplay(celltable);
			List<JourneyPassenger> list = dataProvider.getList();
			for (JourneyPassenger contact :  result) {
				list.add(contact);
			}

			ListHandler<JourneyPassenger> FromcolumnSortHandler = new ListHandler<JourneyPassenger>(list);
			FromcolumnSortHandler.setComparator(FromColumn,
					new Comparator<JourneyPassenger>() {
				public int compare(JourneyPassenger o1, JourneyPassenger o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.From.compareTo(o2.From) : 1;}
					return -1;
				}
			});
			ListHandler<JourneyPassenger> TocolumnSortHandler = new ListHandler<JourneyPassenger>(list);
			TocolumnSortHandler.setComparator(ToColumn,
					new Comparator<JourneyPassenger>() {
				public int compare(JourneyPassenger o1, JourneyPassenger o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.To.compareTo(o2.To) : 1;}
					return -1;
				}
			});
			ListHandler<JourneyPassenger> DatecolumnSortHandler = new ListHandler<JourneyPassenger>(list);
			DatecolumnSortHandler.setComparator(DateColumn,
					new Comparator<JourneyPassenger>() {
				public int compare(JourneyPassenger o1, JourneyPassenger o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.date.compareTo(o2.date) : 1;}
					return -1;
				}
			});

			ListHandler<JourneyPassenger> DrivercolumnSortHandler = new ListHandler<JourneyPassenger>(list);
			DatecolumnSortHandler.setComparator(DriverColumn,
					new Comparator<JourneyPassenger>() {
				public int compare(JourneyPassenger o1, JourneyPassenger o2) {
					if (o1 == o2) {return 0;}
					if (o1 != null) {return (o2 != null) ? o1.Passenger.compareTo(o2.Passenger) : 1;}
					return -1;
				}
			});


			celltable.addColumnSortHandler(FromcolumnSortHandler);
			celltable.addColumnSortHandler(TocolumnSortHandler);
			celltable.addColumnSortHandler(DatecolumnSortHandler);
			celltable.addColumnSortHandler(DrivercolumnSortHandler);


			if(clientFactory.getMapView().getDriverRadioButton().getValue()==true){
				celltable.addColumn( new Column<JourneyPassenger, JourneyPassenger>(new ActionCell<JourneyPassenger>( "add Passenger", new Delegate<JourneyPassenger>( )
						{@Override
					public void execute(final JourneyPassenger object) {
							addpassengertojourney(object,idnumber);

						}
						}))
						{@Override
					public JourneyPassenger getValue(JourneyPassenger object) {
							return object;
						}
						} );
			}
		}
	}

	private void adddrivertojourney(final Journey p, String journeypassidnumber){
		clientFactory.getJPSA().getJourneyById(journeypassidnumber, new AsyncCallback<JourneyPassenger>(){

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Fail to get by id");
			}

			@Override
			public void onSuccess(final JourneyPassenger result) {
				clientFactory.getJSA().getJourneyByIdandAddWaypoints(p.getId(),result, new AsyncCallback<Journey>(){
					@Override
					public void onFailure(Throwable caught) {
						Window.alert("fail to addwp");
					}
					@Override
					public void onSuccess(final Journey resultat) {
						if(resultat==null){
							Window.alert("addwp null");
						}
						else{
							Window.alert("wp added");
							MessageViewConstants mvc = GWT.create(MessageViewConstants.class);
							Date today = new Date();
							Message message = new Message(resultat.getDriver(),result.getPassenger(),mvc.notifydriv(),today.toString());
							sendmessage(message);

							result.setDriverName(resultat.getDriver());
							clientFactory.getJPSA().adddriver(result, new AsyncCallback<JourneyPassenger>(){
								@Override
								public void onFailure(Throwable caught) {
									Window.alert("nine nine!");
								}
								@Override
								public void onSuccess(JourneyPassenger result) {
									Window.alert("voila qui est parfait!");
								}

							});



						}
					}
				});

			}

		});


	}

	private void addpassengertojourney(final JourneyPassenger jp, String journeyidnumber){

		clientFactory.getJSA().getJourneyByIdandAddWaypoints(journeyidnumber,jp, 
				new AsyncCallback<Journey>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("fail to addwp");
			}
			@Override
			public void onSuccess(final Journey resultat) {
				if(resultat==null){
					Window.alert("addwp null");
				}
				else{
					Window.alert("wp added");
					MessageViewConstants mvc = GWT.create(MessageViewConstants.class);
					Date today = new Date();
					Message message = new Message(resultat.getDriver(),jp.getPassenger(),mvc.notifypass(),today.toString());
					sendmessage(message);
					jp.setDriverName(resultat.getDriver());
					clientFactory.getJPSA().adddriver(jp, new AsyncCallback<JourneyPassenger>(){
						@Override
						public void onFailure(Throwable caught) {
							Window.alert("nine nine!");
						}

						@Override
						public void onSuccess(JourneyPassenger result) {
							Window.alert("voila qui est parfait!");


						}

					});

				}
			}
		});

	}

	private void sendmessage(Message message){
		clientFactory.getMSA().AddMessage(message, new AsyncCallback<Message>(){

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("fail to send");
			}
			@Override
			public void onSuccess(Message result) {
				Window.alert("notification send");
			}

		});

	}


}